import os
import sys
import platform
from pmapi import progbar

if platform.system() == 'Linux':
    LOCK_PATH = "/tmp"+os.sep+"pm.lock"
else:
    LOCK_PATH = os.getenv("windir")+os.sep+"Temp"+os.sep+"pm.lock"


class Lock:
    def __init__(self, lockname) -> None:
        if os.path.exists(LOCK_PATH):
            with open(LOCK_PATH, "r") as file:
                w = file.read().replace("\n", ", ")  # 进程信息
            sys.stdout.write("Wait Lock in "+LOCK_PATH +
                             " (If PM not running, please remove this file)\n")
            wait_prog = progbar.ProgressPoint(
                templete="Wait Lock... ("+w+") {bar}")
            wait_prog.wait_in_anim(
                0.2, lambda n: os.path.exists(LOCK_PATH))
        with open(LOCK_PATH, "w") as file:
            file.write(str(os.getpid())+"\n"+lockname)

    def remove(self) -> None:
        os.remove(LOCK_PATH)
